package cn.turboinfo.fuyang.api.domain.admin.usecase.staff;

import cn.turboinfo.fuyang.api.domain.common.service.company.HousekeepingCompanyService;
import cn.turboinfo.fuyang.api.domain.common.service.staff.HousekeepingStaffService;
import cn.turboinfo.fuyang.api.domain.common.service.user.SysUserService;
import cn.turboinfo.fuyang.api.domain.common.service.user.UserCredentialService;
import cn.turboinfo.fuyang.api.domain.common.service.user.UserLoginService;
import cn.turboinfo.fuyang.api.domain.common.service.user.UserTypeRelService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.entity.admin.enumeration.login.AdminLoginOperation;
import cn.turboinfo.fuyang.api.entity.common.enumeration.staff.StaffStatus;
import cn.turboinfo.fuyang.api.entity.common.enumeration.user.LoginNameType;
import cn.turboinfo.fuyang.api.entity.common.exception.product.ProductException;
import cn.turboinfo.fuyang.api.entity.common.pojo.staff.HousekeepingStaff;
import cn.turboinfo.fuyang.api.entity.common.pojo.user.SysUser;
import cn.turboinfo.fuyang.api.entity.common.pojo.user.SysUserCreator;
import cn.turboinfo.fuyang.api.entity.common.pojo.user.UserLogin;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import net.sunshow.toolkit.core.base.enums.EnableStatus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Component
public class HousekeepingStaffReviewUseCase extends AbstractUseCase<HousekeepingStaffReviewUseCase.InputData, HousekeepingStaffReviewUseCase.OutputData> {
    private final HousekeepingStaffService housekeepingStaffService;
    private final UserLoginService userLoginService;
    private final SysUserService sysUserService;
    private final UserTypeRelService userTypeRelService;
    private final UserCredentialService userCredentialService;
    private final HousekeepingCompanyService housekeepingCompanyService;

    @Override
    protected OutputData doAction(InputData inputData) {
        val staff = housekeepingStaffService.getById(inputData.id).orElse(new HousekeepingStaff());
        if (!inputData.getCompanyId().equals(staff.getCompanyId())) {
            throw new ProductException("没有操作权限");
        }

        String loginName = staff.getContactMobile();

        // 从登录方式检查登记的手机号用户是否存在
        Long userId;
        List<UserLogin> loginList = userLoginService.findByLoginNameAndLoginNameType(loginName, LoginNameType.PHONE_NUM);
        if (inputData.getStatus().equals(StaffStatus.PUBLISHED)) {
            if (loginList.isEmpty()) {
                log.error("用户不存在, 自动创建, loginName={}", loginName);
                // 创建用户
                SysUserCreator.Builder builder = SysUserCreator.builder()
                        .withMobile(loginName)
                        .withUsername(loginName)
                        .withStatus(EnableStatus.ENABLED)
                        .withLoginOperation(AdminLoginOperation.MODIFY_PASSWORD);
                // 设置初始密码为法人身份证后六位
                SysUser sysUser = sysUserService.save(builder.build(), null);
                createStaffRel(sysUser.getId(), staff);
            } else {
                // 用户已存在, 检查是否已有家政员关联
                userId = loginList.get(0).getUserId();
                if (!userTypeRelService.hasStaffRel(userId, staff.getId())) {
                    createStaffRel(userId, staff);
                }
            }
        } else if (!loginList.isEmpty()) {
            userTypeRelService.deleteStaffRel(loginList.get(0).getUserId(), staff.getId());
        }

        housekeepingStaffService.updateStatus(inputData.getId(), inputData.getStatus());

        //更新企业家政员数量
        housekeepingCompanyService.updateStaffNum(staff.getCompanyId(), housekeepingStaffService.countByCompanyId(staff.getCompanyId()));

        return OutputData.builder()
                .build();
    }

    private void createStaffRel(Long userId, HousekeepingStaff staff) {
        // 如果之前没设置过密码 设置初始密码为法人身份证后六位
        if (userCredentialService.findUserDefault(userId).isEmpty()) {
            userCredentialService.save(userId, StringUtils.substring(staff.getIdCard(), -6));
        }
        // 创建相应的关联
        userTypeRelService.createStaffRel(userId, staff.getId());
    }

    @EqualsAndHashCode(
            callSuper = true
    )
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputData extends AbstractUseCase.InputData {
        @NotNull(
                message = "编码不能为空"
        )
        private Long id;

        @NotNull(
                message = "公司id不能为空"
        )
        private Long companyId;

        @NotNull(
                message = "状态不能为空"
        )
        private StaffStatus status;
    }

    @EqualsAndHashCode(callSuper = true)
    @Data
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {
    }
}
